import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';
import { ObjectType } from '../types';
import UserModel from '../models/user.model';

export interface UserState extends ObjectType {
  userId: string;
  isAdmin: boolean;
}

export interface UserToken extends ObjectType, Partial<UserModel> {
  id: string;
}

dotenv.config();

/**
 * 生成 JWT Token
 * @param {UserToken} payload - 要编码到 token 中的有效负载
 * @param {string} secret - 用于签名的密钥
 * @param {jwt.SignOptions} options - 选项，例如过期时间
 * @returns {string} - 返回生成的 token
 */
export const generateToken = (
  payload: UserToken,
  secret: string = process.env.JWT_SECRET as string,
  options: jwt.SignOptions = { expiresIn: process.env.JWT_EXPIRES_IN || '7d' },
): string => {
  return jwt.sign(payload, secret, options);
};

/**
 * 校验 JWT Token
 * @param {string} token - 要校验的 token
 * @param {string} secret - 用于签名的密钥
 * @returns {UserToken} - 返回解码后的有效负载或错误信息
 */
export const verifyToken = (token: string, secret: string = process.env.JWT_SECRET as string): UserToken => {
  try {
    return jwt.verify(token, secret) as UserToken;
  } catch (error: any) {
    throw error;
  }
};
